<template>
	<div class="add-rule">
		<el-card class="rule-card">
			<template #header>
				<div class="card-btn">
					<el-button @click="$router.back()">
						<el-icon><arrow-left /></el-icon>
						返回
					</el-button>
					<!-- <el-button
						@click="submitForm"
						type="primary">
						保存
					</el-button> -->
				</div>
			</template>
			<div class="rule-container">
				<el-form
					ref="ruleFormRef"
					:model="ruleForm"
					:inline="true"
					:rules="rules"
					label-width="auto"
					class="demo-form-inline"
					:size="formSize"
					status-icon>
					<div class="container-resource">
						<p class="resource-title">资源</p>
						<div class="resource-form">
							<el-form-item
								label="服务资源类型"
								prop="region"
								style="width: 500px">
								<el-select
									v-model="ruleForm.region"
									placeholder="请选择..."
									clearable
									:disabled="formState == 'edit'"
									filterable>
									<el-option
										v-for="item in resourceTypeOpts"
										:label="item.label"
										:key="item.id"
										:value="item.value" />
								</el-select>
							</el-form-item>
							<el-form-item
								label="服务资源名称"
								prop="region"
								style="width: 500px">
								<el-select
									v-model="ruleForm.region"
									placeholder="请选择..."
									clearable
									filterable>
									<el-option
										label="Zone one"
										value="shanghai" />
								</el-select>
							</el-form-item>
						</div>
						<div class="resource-flow">
							<p class="flow-title">流量分类标识</p>
							<div class="flow-form">
								<el-form-item
									label="协议类型"
									prop="region"
									style="width: 500px"
									label-position="left">
									<el-input
										disabled
										v-model="ruleForm.region" />
								</el-form-item>
							</div>
							<div class="flow-address">
								<el-form-item
									label="路径"
									prop="name"
									style="width: 500px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									label=""
									prop="name">
									<el-switch
										v-model="ruleForm.switchPath"
										inline-prompt
										active-value="1"
										inactive-value="2" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.switchPath == '1'"
									label="精细化设置"
									prop="set"
									style="width: 390px"
									label-position="left">
									<el-input v-model="ruleForm.set" />
								</el-form-item>
							</div>
							<el-form-item
								v-if="ruleForm.switchPath == '1'"
								label="请求参数"
								prop="action"
								style="width: 994px"
								label-position="left">
								<el-input v-model="ruleForm.action" />
							</el-form-item>
							<el-form-item
								v-if="ruleForm.switchPath == '1'"
								label="请求头"
								prop="action"
								style="width: 994px"
								label-position="left">
								<el-input v-model="ruleForm.action" />
							</el-form-item>
							<el-form-item
								v-if="ruleForm.switchPath == '1'"
								label="请求体"
								prop="action"
								style="width: 994px"
								label-position="left">
								<el-input v-model="ruleForm.action" />
							</el-form-item>
						</div>
					</div>
					<div class="container-rule">
						<p class="rule-title">规则</p>
						<div class="rule-form">
							<el-form-item
								label="规则类型"
								prop="ruleType"
								style="width: 500px">
								<el-select
									v-model="ruleForm.ruleType"
									placeholder="请选择..."
									clearable
									@change="ruleTypeChange"
									filterable>
									<el-option
										v-for="item in ruleTypeOpts"
										:label="item.label"
										:key="item.id"
										:value="item.value" />
								</el-select>
							</el-form-item>
							<el-form-item
								v-if="ruleTypeAlgorithmOpts.length > 0"
								label=""
								prop="ruleTypeAlgorithm"
								style="width: 500px">
								<el-select
									v-model="ruleForm.ruleTypeAlgorithm"
									placeholder="请选择..."
									clearable
									filterable>
									<el-option
										v-for="item in ruleTypeAlgorithmOpts"
										:label="item.label"
										:key="item.id"
										:value="item.value" />
								</el-select>
							</el-form-item>
						</div>
						<div class="rule-format">
							<p class="format-title">规则参数</p>
							<div class="format-form">
								<!-- 限流 - Sentinel线程池 -->
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['4'].includes(ruleForm.ruleTypeAlgorithm)"
									label="线程数阈值"
									prop="name"
									style="width: 994px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>

								<!-- 限流 - Gien混合令牌桶 -->
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['TOKEN_BUCKET'].includes(ruleForm.ruleTypeAlgorithm)"
									label="容量"
									prop="name"
									style="width: 994px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['TOKEN_BUCKET'].includes(ruleForm.ruleTypeAlgorithm)"
									label="峰值阈值"
									prop="name"
									style="width: 994px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['TOKEN_BUCKET'].includes(ruleForm.ruleTypeAlgorithm)"
									label="间隔周期"
									prop="name"
									style="width: 750px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['TOKEN_BUCKET'].includes(ruleForm.ruleTypeAlgorithm)"
									label=""
									prop="region"
									style="width: 210px"
									label-position="left">
									<el-select
										v-model="ruleForm.region"
										placeholder="请选择..."
										clearable
										filterable>
										<el-option
											label="毫秒"
											value="shanghai" />
										<el-option
											label="秒"
											value="shanghai" />
										<el-option
											label="分钟"
											value="shanghai" />
									</el-select>
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['TOKEN_BUCKET'].includes(ruleForm.ruleTypeAlgorithm)"
									label="填充数"
									prop="name"
									style="width: 994px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>

								<!-- 限流 - Gien滑动窗口/Sentinel滑动窗口 -->
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['SEN_SLIDING_WINDOW', 'GIEN_SLIDING_WINDOW'].includes(ruleForm.ruleTypeAlgorithm)"
									label="窗口数"
									prop="name"
									style="width: 994px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['SEN_SLIDING_WINDOW', 'GIEN_SLIDING_WINDOW'].includes(ruleForm.ruleTypeAlgorithm)"
									label="采集周期"
									prop="name"
									style="width: 750px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['SEN_SLIDING_WINDOW', 'GIEN_SLIDING_WINDOW'].includes(ruleForm.ruleTypeAlgorithm)"
									label=""
									prop="region"
									style="width: 210px"
									label-position="left">
									<el-select
										v-model="ruleForm.region"
										placeholder="请选择..."
										clearable
										filterable>
										<el-option
											label="毫秒"
											value="shanghai" />
										<el-option
											label="秒"
											value="shanghai" />
										<el-option
											label="分钟"
											value="shanghai" />
									</el-select>
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'RateLimit' && ['SEN_SLIDING_WINDOW', 'GIEN_SLIDING_WINDOW'].includes(ruleForm.ruleTypeAlgorithm)"
									label="请求数阈值"
									prop="name"
									label-position="left"
									style="width: 994px">
									<el-input v-model="ruleForm.name" />
								</el-form-item>

								<!-- 熔断 - 错误率熔断 -->
								<el-form-item
									v-if="ruleForm.ruleType == 'CircuitBreaker' && ['ERROR_RATE_CIRCUIT_BREAKER', 'SLOW_RATE_CIRCUIT_BREAKER'].includes(ruleForm.ruleTypeAlgorithm)"
									label="阈值"
									prop="name"
									label-position="left"
									style="width: 994px">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'CircuitBreaker' && ['ERROR_RATE_CIRCUIT_BREAKER', 'SLOW_RATE_CIRCUIT_BREAKER'].includes(ruleForm.ruleTypeAlgorithm)"
									label="持续时长"
									prop="name"
									style="width: 750px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'CircuitBreaker' && ['ERROR_RATE_CIRCUIT_BREAKER', 'SLOW_RATE_CIRCUIT_BREAKER'].includes(ruleForm.ruleTypeAlgorithm)"
									label=""
									prop="region"
									style="width: 210px"
									label-position="left">
									<el-select
										v-model="ruleForm.region"
										placeholder="请选择..."
										clearable
										filterable>
										<el-option
											label="毫秒"
											value="shanghai" />
										<el-option
											label="秒"
											value="shanghai" />
										<el-option
											label="分钟"
											value="shanghai" />
									</el-select>
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'CircuitBreaker' && ['ERROR_RATE_CIRCUIT_BREAKER', 'SLOW_RATE_CIRCUIT_BREAKER'].includes(ruleForm.ruleTypeAlgorithm)"
									label="统计时长"
									prop="name"
									style="width: 750px"
									label-position="left">
									<el-input v-model="ruleForm.name" />
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'CircuitBreaker' && ['ERROR_RATE_CIRCUIT_BREAKER', 'SLOW_RATE_CIRCUIT_BREAKER'].includes(ruleForm.ruleTypeAlgorithm)"
									label=""
									prop="region"
									style="width: 210px"
									label-position="left">
									<el-select
										v-model="ruleForm.region"
										placeholder="请选择..."
										clearable
										filterable>
										<el-option
											label="毫秒"
											value="shanghai" />
										<el-option
											label="秒"
											value="shanghai" />
										<el-option
											label="分钟"
											value="shanghai" />
									</el-select>
								</el-form-item>
								<el-form-item
									v-if="ruleForm.ruleType == 'CircuitBreaker' && ['ERROR_RATE_CIRCUIT_BREAKER', 'SLOW_RATE_CIRCUIT_BREAKER'].includes(ruleForm.ruleTypeAlgorithm)"
									label="最小请求数"
									prop="name"
									label-position="left"
									style="width: 994px">
									<el-input v-model="ruleForm.name" />
								</el-form-item>

								<!-- 通用 -->
								<el-form-item
									v-if="['RateLimit', 'CircuitBreaker', 'Fallback'].includes(ruleForm.ruleType)"
									label="超限行为"
									prop="action"
									label-position="left"
									style="width: 994px">
									<el-select
										v-model="ruleForm.action"
										placeholder="请选择..."
										clearable
										filterable>
										<el-option
											label="Zone one"
											value="shanghai" />
									</el-select>
								</el-form-item>
							</div>
						</div>
					</div>
					<div class="container-time">
						<p class="time-title">时间</p>
						<div class="time-form">
							<el-form-item
								label="生效时间"
								prop="region"
								style="width: 640px">
								<el-date-picker
									v-model="ruleForm.region"
									type="date"
									placeholder="请选择..." />
							</el-form-item>
							<el-form-item
								label="失效时间"
								prop="region"
								style="width: 500px">
								<el-date-picker
									v-model="ruleForm.region"
									type="date"
									placeholder="请选择..." />
							</el-form-item>
						</div>
					</div>
				</el-form>
			</div>

			<div class="rule-footer">
				<el-button
					@click="submitForm"
					size="large"
					type="primary">
					保存
				</el-button>
			</div>
		</el-card>
	</div>
</template>
<script lang="ts" setup>
	import { onBeforeMount, onMounted, reactive, ref } from 'vue'
	import { getItem } from '@/utils/storage'
	import { useRoute } from 'vue-router'

	const route = useRoute()

	const formState = ref('add')

	const formSize = ref<any>('default')
	const ruleFormRef = ref<any>()
	const ruleForm = ref<any>({
		name: '',
		region: '',
		switch: '',
		switchPath: '',
		set: '',
		ruleType: 'RateLimit',
		ruleTypeAlgorithm: 'SEN_SLIDING_WINDOW',
		action: '',
	})

	// TODO 处理传参
	// 1. form表单没有的数据 - 1, form表单可能对应的数据 - 2
	// 2. 确认字典
	const requestForm = ref<any>({
		apiVersion: '',
		kind: '', //  2 规则类型：{RateLimit：限流，CircuitBreaker：熔断，Fallback：降级}
		metadata: {
			uid: '',
			name: '', //2 资源名称  ???  服务资源名称
			namespace: '',
			version: '',
			labels: {
				// "app.gientech.com/name":"Test"
			},
		},
		spec: {
			resource: '',
			rules: [
				// 限流规则描述  为什么是数组
				{
					name: '',
					description: '',
					disable: '',
					startTimestamp: '', //2 生效时间  - 临时规则开始时间，精确到毫秒
					endTimestamp: '', //2  失效时间 - 临时规则结束时间，精确到毫秒
					protocol: '',
					method: {
						// ???  精细化设置
						//method定义，精确匹配：exact,  表达式匹配：http_custom_op
						// "http_custom_op": "/greatyu/v1/poc/queryUser/{id}"
					},
					arguments: [
						// 2 请求参数
						{
							type: '', //参数类型
							key: '', //产生对应的key
							value: {
								in: '', //匹配方式：exact,prefix,regex,not_equals,in,not_in,range,tcp_custom_op,http_custom_op
							},
						},
					],
				},
			],
			position: '',
			// 限流
			rateLimitPolicy: {
				apiVersion: '',
				kind: '',
				spec: {
					mode: '',
					failover: '',
					grade: '',
					// 缺少 超限行为
					algorithm: {
						kind: '', // 2 规则类型 - 算法类型
						// GIEN滑动窗口算法/Sentinel滑动窗口算法
						gienSlidingWindow: {
							windowSize: 2, // 2 窗口数
							statDurationMs: 1000, // 采集周期 - 采样周期(单位为毫秒)
							triggerThreshold: 200, // 2 阈值
						},
						// 令牌桶算法
						// 缺少 峰值阈值
						tokenBucket: {
							capacity: 1000, //容量
							fillIntervalMs: 500, //间隔周期，单位为 ms
							fillCount: 200, //填充数
							isAutoPutToken: false, // 1 没有这个参数 ??? 是否自动填充令牌，true:是，false:否
						},
						// 线程数限流(没有这个字典)
						threadCountLimit: {
							threadCountThreshold: 100, //线程数阈值
						},
						// 本地均摊集群限流(没有这个字典)
						localEqualizeClusterLimit: {
							totalThreshold: 1000, //集群阈值
							singleThreshold: 1000, //采样周期
							instanceNum: 1000, //实例数
							instanceNum: 1000, //采样周期，单位为 ms(字段名称重复)
						},
					},
				},
			},
			fallback: {
				apiVersion: '',
				kind: 'Fallback',
				spec: {
					rules: [
						{
							name: '',
							description: '',
							disable: false,
							algorithm: {
								kind: '',
							},
							config: {
								strategy: '',
								customMessage: {
									message: '',
								},
							},
						},
					],
					// 熔断
					resource: '',
				},

				//  熔断
				metadata: {
					uid: null,
					name: '',
					namespace: 'default',
				},
			},
			// 算法描述
			algorithm: {
				kind: 'SLOW_RATE_CIRCUIT_BREAKER',
				// 错误率熔断算法
				errorRateCircuitBreaker: {
					triggerThreshold: 0.5, // 阈值
					statDurationMs: 60000, // 统计时长(两个文档描述不一致)
					recoveryTimeoutMs: 60000, // 持续时长(两个文档描述不一致)
					minRequestAmount: 5, // 错误请求数
					// 1 错误条件 ??? 页面没有
					errorConditions: {
						inputType: 'EXCEPTION', //RET_CODE：返回码，EXCEPTION：异常, BODY: body信息
					},
				},
				slowRateCircuitBreaker: {
					triggerThreshold: 0.5, // 阈值
					statDurationMs: 0.5, // 持续时间(两个文档描述不一致)
					recoveryTimeoutMs: 0.5, // 统计时间(两个文档描述不一致)
					minRequestAmount: 0.5, // 最小请求数
					maxAllowedRtMs: 0.5, // 临界值(页面没有这个数据)
				},
			},
			// 降级
			hosts: [{ name: '' }],
			config: {
				strategy: 'REJECT',
				customMessage: {
					message: 'blocked by manual fallback',
				},
			},
		},

		//  熔断
		circuitBreakerPolicy: {
			apiVersion: '',
			kind: 'CircuitBreakerPolicy',
			metadata: {
				uid: 1234,
				name: 'Circuit Breaker Policy',
				namespace: 'default',
			},
		},
	})
	// 这里的规则是  降级吗
	const ruleTypeOpts = reactive([
		{
			label: '限流',
			value: 'RateLimit',
			id: 1,
		},
		{
			label: '熔断',
			value: 'CircuitBreaker',
			id: 2,
		},
		{
			label: '规则',
			value: 'Fallback',
			id: 3,
		},
	])

	const resourceTypeOpts = reactive([
		{
			label: '服务资源1',
			value: '1',
			id: 1,
		},
	])

	const ruleTypeAlgorithmOpts = <any>ref([])

	const rules = reactive<any>({
		name: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
		region: [
			{
				required: true,
				message: '内容不能为空',
				trigger: 'change',
			},
		],
	})

	const submitForm = (val: any) => {
		console.log('%c Line:211 🍬 val', 'color:#42b983', val)

// 		url:/rule/{apiVersion}/namespaces/{namespace}/kinds/{kind}/names
// 	{apiVersion}: api版本
// 	{namespace}: namespace, 默认为default
// 	{kind}: 规则类型，RateLimit：限流，CircuitBreaker：熔断，Fallback：降级
// 请求方式：post
	}

	const getStatus = () => {
		let state: any = route.query.state
		formState.value = state
		if (state == 'edit') {
			ruleForm.value = {
				name: '1',
				region: '1',
				switch: '1',
				set: '1',
				ruleType: 'RateLimit',
				ruleTypeAlgorithm: 'SEN_SLIDING_WINDOW',
				action: '1',
			}
		}
	}

	const ruleTypeChange = (val: string) => {
		if (val == 'RateLimit') {
			getRuleTypeAlgorithmOpts()
			ruleForm.value.ruleTypeAlgorithm = 'SEN_SLIDING_WINDOW'
		} else if (val == 'CircuitBreaker') {
			ruleForm.value.ruleTypeAlgorithm = 'ERROR_RATE_CIRCUIT_BREAKER'
			ruleTypeAlgorithmOpts.value = [
				{
					label: '错误率熔断算法',
					value: 'ERROR_RATE_CIRCUIT_BREAKER',
					id: 1,
				},
				{
					label: '慢调用熔断算法',
					value: 'SLOW_RATE_CIRCUIT_BREAKER',
					id: 2,
				},
				// {
				// 	label: '线程数限流',
				// 	value: 'THREAD_COUNT_LIMIT',
				// 	id: 3,
				// },
				// {
				// 	label: '本地均摊集群限流',
				// 	value: 'LOCAL_EQUALIZE_CLUSTER_LIMIT',
				// 	id: 4,
				// },
			]
		} else if (val == 'Fallback') {
			ruleTypeAlgorithmOpts.value = []
			ruleForm.value.ruleTypeAlgorithm = ''
		} else {
			ruleTypeAlgorithmOpts.value = []
			ruleForm.value.ruleTypeAlgorithm = ''
		}
	}

	// TODO: 算法字典
	const getRuleTypeAlgorithmOpts = () => {
		ruleTypeAlgorithmOpts.value = [
			{
				label: 'Sentinel滑动窗口',
				value: 'SEN_SLIDING_WINDOW',
				id: 1,
			},
			{
				label: 'Gien滑动窗口',
				value: 'GIEN_SLIDING_WINDOW',
				id: 2,
			},
			{
				label: '令牌桶算法',
				value: 'TOKEN_BUCKET',
				id: 3,
			},
			{
				label: 'Sentinel线程池',
				value: '4',
				id: 4,
			},
			// {
			// 	label: '手动降级算法',
			// 	value: 'MANUAL_DEGRADE',
			// 	id: 5,
			// },
		]
	}
	const getPageList = () => {
		// 		url:/rule/{apiVersion}/namespaces/{namespace}/kinds/{kind}/names/{name}?page=1&size=10
		// 	{apiVersion}: api版本
		// 	{namespace}: namespace, 默认为default
		// 	{kind}: 规则类型，RateLimit：限流，CircuitBreaker：熔断，Fallback：降级
		// 	{name}：资源名称
		// 	page: 获取对应页
		// 	size: 每页多少条
		// 请求方式：get

		pageJson


		//  页面数据
		// 资源 / 规则类型 / 规则状态 / 生效点 / 创建人 / 最近修改时间 / 生效时间 / 失效时间



		// TODO 获取指定规则  是什么意思
	}

	onMounted(() => {
		getStatus()
		getRuleTypeAlgorithmOpts()
		getPageList()
	})

	defineExpose({})
</script>

<style lang="scss" scoped>
	.add-rule {
		margin-bottom: 50px;
		.rule-card {
			.card-btn {
				display: flex;
				justify-content: space-between;
			}
		}
		.rule-container {
			width: 100%;
			padding: 0px 20px;
			.container-resource {
				width: 100%;
				border-bottom: 1px dashed #ccc;
				.resource-title {
					font-size: 16px;
					font-weight: 600;
				}
				.resource-form {
					width: 100%;
				}
				.resource-flow {
					margin-bottom: 20px;
					padding: 20px 20px 0px 36px;
					border-radius: 6px;
					background-color: #eee;
					// padding: 20px;
					.flow-title {
						font-weight: 600;
					}
				}
			}
			.container-rule {
				width: 100%;
				margin-top: 20px;
				border-bottom: 1px dashed #ccc;
				.rule-title {
					font-size: 16px;
					font-weight: 600;
				}
				.rule-form {
				}
				.rule-format {
					padding: 20px 20px 0px 36px;
					border-radius: 6px;
					background-color: #eee;
					margin-bottom: 20px;
					.format-title {
						font-weight: 600;
					}
					.format-form {
						width: 100%;
					}
				}
			}
			.container-time {
				width: 100%;
				margin-top: 20px;
				// border-bottom: 1px dashed #ccc;
				.time-title {
					font-weight: 600;
					font-size: 16px;
				}
				.time-form {
					padding: 20px 20px 0px 36px;
					border-radius: 6px;
					background-color: #eee;
				}
			}
		}
		.rule-footer {
			margin-top: 20px;
			display: flex;
			justify-content: center;
		}
	}
	// form
	// :deep(.el-select__wrapper) {
	// 	width: 180px;
	// }
</style>
